<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Post\ChangePrice;
use App\Admin\Actions\Post\CheckOrder;
use App\Admin\Actions\Post\Refund;
use App\Models\Order;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\DB;

class OrderController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '订单';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order());
        $grid->disableExport();
        $grid->filter(function($filter){

            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            //$company = DB::table('company')->pluck('name','id');
            // 在这里添加字段过滤器

            $filter->column(1/2,function ($filter){
                $filter->equal('pay_status','支付状态')->select(['0'=>'待支付','1'=>'已支付']);
                $filter->equal('check_status','核销状态')->select(['0'=>'待核销','1'=>'已核销']);
            });

            $filter->column(1/2,function ($filter){
                //$filter->equal('company_id','所属公司')->select($company);

                $filter->where(function ($query) {

                    $query->whereHas('user', function ($query) {
                        $query->where('name', 'like', "%{$this->input}%")->orWhere('nickname', 'like', "%{$this->input}%")->orWhere('mobile', 'like', "%{$this->input}%");
                    });

                }, '用户名或手机');
                $filter->like('order_sn','订单编号');
            });
            $filter->between('created_at', '创建时间')->datetime();

        });
        $grid->model()->orderBy('id', 'desc');
        $grid->column('id', __('ID'));
        $grid->column('order_sn', __('订单单号'))->expand(function ($model) {

            $order_goods = $model->goods()->get()->map(function ($order_goods) {
                return $order_goods->only(['id', 'goods_name', 'goods_img','goods_price','num','total_money']);
            })->toArray();

            foreach ($order_goods as $k=>$v){

                $url = "http://lxxybucket.oss-cn-hangzhou.aliyuncs.com/{$v['goods_img']}";
                $order_goods[$k]['goods_img'] = '<a href="'.$url.'" class="grid-popup-link">
    <img src="'.$url.'" style="max-width:50px;max-height:50px" class="img img-thumbnail">
</a>';

            }

            return new Table(['ID', '商品名称', '商品图片','价格','数量','总价'], $order_goods);
        });

        $grid->column('user.name', __('用户名称'))->display(function ($total) {


            if (!$total) {
                if($this->user)
                    return $this->user->nickname;
            }
            return $total;

        });
        //$grid->column('goods.name', __('商品名称'));
        $grid->column('user.mobile', __('电话'));


        $grid->column('money', __('实付金额'));

        $grid->column('pay_status', __('支付状态'))->using(['0' => '待支付', '1' => '已支付'])->label([
                                                                                                    0 => 'default',
                                                                                                    1 => 'success',
                                                                                                         ]);
        $grid->column('check_status', __('核销状态'))->using(['0' => '待核销', '1' => '已核销'])->label([
            0 => 'default',
            1 => 'success',
        ]);

        $grid->column('order_status', __('订单状态'))->using(['0' => '待支付', '1' => '待核销','2'=>'已完成','3'=>'已退款'])->label([
            0 => 'default',
            1 => 'default',
            2 => 'success',
            3 => 'success'
        ]);
        $grid->column('pay_time', __('支付时间'));
        $grid->column('check_time', __('核销时间'));
        $grid->column('created_at', __('创建时间'));

        $grid->actions(function($actions){
            $actions->disableDelete();
            $actions->disableEdit();
            //$actions->disableView();

            if($actions->row->pay_status==0){

                $actions->add(new ChangePrice());
            }

            if($actions->row->pay_status==1 && $actions->row->check_status==0){

                $actions->add(new CheckOrder());
                $actions->add(new Refund());
            }

        });

        //$grid->disableActions();

        $grid->disableBatchActions();



 //       $grid->export(function ($export) {


//            $export->column('pay_status', function ($value, $original) {
//               return $this->cutstr_html($value);
//            });
//
//            $export->column('order_sn', function ($value, $original) {
//                return '`'.$value;
//            });


 //       });

        return $grid;
    }

    //去掉文本中的HTML标签
    public function cutstr_html($string, $length = 0, $ellipsis = '…')
    {
        $string = strip_tags($string);
        $string = preg_replace('/\n/is', '', $string);
        $string = preg_replace('/ |　/is', '', $string);
        $string = preg_replace('/ /is', '', $string);
        $string = preg_replace('/<br \/>([\S]*?)<br \/>/','<p>$1<\/p>',$string);
        preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $string);
        if (is_array($string) && !empty($string[0])) {
            if (is_numeric($length) && $length) {
                $string = join('', array_slice($string[0], 0, $length)) . $ellipsis;
            } else {
                $string = implode('', $string[0]);
            }
        } else {
            $string = '';
        }
        return $string;
    }


    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));


        $show->field('note', __('订单备注'));
        $show->field('refund_note', __('退款备注'));
        $show->field('price_note', __('改价备注'));


        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Order());

        $form->text('order_sn', __('Order sn'))->readonly();


        $form->text('money', __('实付金额'))->readonly();

        $form->select('status', __('订单状态'))->options(['1'=>'待发货','2'=>'已发货','3'=>'已完成','4'=>'退款中','5'=>'已退款',]);
        $form->textarea('note', __('订单备注'));

        return $form;
    }
}
